<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      style="border-bottom: 1px solid #c9c9c9; margin-bottom: 30px"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="订单编号" style="margin-right:50px;" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="老人姓名" style="margin-right:50px;" prop="elderlyName">
        <el-input
          v-model="queryParams.elderlyName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单人" style="margin-right:50px;" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入下单人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style=" width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="订单状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          @change="handleStatusChange"
          placeholder="请选择订单状态"
          clearable
        >
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" style="background-color: #266FE8; color: white;" @click="handleQuery"
          >搜索</el-button
        >
        <el-button  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="status-buttons">
      <el-button
        v-for="dict in order_status"
        :key="dict.value"
        :class="{
          'active': queryParams.orderStatus === dict.value,
          'default-btn': queryParams.orderStatus !== dict.value
        }"
        @click="handleStatusChange(dict.value)"
      >
        {{ dict.label }}
      </el-button>
      <!-- 全部按钮 -->
      <el-button
        :class="{
          'active': queryParams.orderStatus === '',
          'default-btn': queryParams.orderStatus !== ''
        }"
        @click="handleStatusChange('')"
      >
        全部
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="managementList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="老人姓名" align="center" prop="elderly.name" />
      <el-table-column label="床位号" align="center" prop="bedNo" />
      <el-table-column
        label="护理项目"
        align="center"
        prop="nursingItem.name"
      />
      <el-table-column label="订单金额" align="center" prop="orderAmount" />
      <el-table-column
        label="期望服务时间"
        align="center"
        prop="expectedServiceTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.expectedServiceTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="下单人"
        align="center"
        prop="sysUser.nickName"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="交易状态" align="center" prop="transactionStatus">
        <template #default="scope">
          <dict-tag
            :options="transaction_status"
            :value="scope.row.transactionStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right" 
        width="220"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="cancle(scope.row)"
            v-hasPermi="['le:management:edit']"
            :disabled="scope.row.orderStatus != 0 || scope.row.transactionStatus != 0"
            >取消</el-button
          >
          <el-button
            link
            type="primary"
            @click="refund(scope.row)"
            v-hasPermi="['le:record:edit']"
            :disabled="scope.row.orderStatus != 1 || scope.row.transactionStatus != 1"
            >退款</el-button
          >
          <el-button
            link
            type="primary"
            @click="check(scope.row)"
            v-hasPermi="['le:management:remove']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 退款原因对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="managementRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="退款原因" prop="refundReason">
          <el-input
            v-model="form.refundReason"
            type="textarea"
            placeholder="请输入退款原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 取消原因对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="managementRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="取消原因" prop="cancleReason">
          <el-input
            v-model="form.cancleReason"
            type="textarea"
            placeholder="请输入取消原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="canclesubmitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Management">
import {
  listManagement,
  getManagement,
  delManagement,
  addManagement,
  updateManagement,
} from "@/api/le/management";
import { listRecord, getRecord, delRecord, addRecord,addRecordPro, updateRecord } from "@/api/le/record"

import { get } from "@vueuse/core";
import { useRouter } from "vue-router";
// 获取路由实例
const router = useRouter();


const { proxy } = getCurrentInstance();
const { order_status, transaction_status } = proxy.useDict(
  "order_status",
  "transaction_status"
);

const managementList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);

const data = reactive({
  form: {},
  refundFrom:{},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    elderlyId: null,
    orderUserId: null,
    createTime: null,
    orderStatus: null,
    cancelReason: null,
    elderlyName:null,
    userName:null
    
  },
  rules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules ,refundFrom } = toRefs(data);

/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && "" != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listManagement(queryParams.value).then((response) => {
    managementList.value = response.rows;
    console.log(managementList);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    elderlyId: null,
    nursingItemId: null,
    orderAmount: null,
    expectedServiceTime: null,
    orderUserId: null,
    createTime: null,
    updateTime: null,
    remark: null,
    orderStatus: null,
    transactionStatus: null,
    cancelReason: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("managementRef");
}

function handleStatusChange(value) {
      // 直接调用原有的查询方法，使用已有的queryParams和接口
      queryParams.value.orderStatus = value;
      this.handleQuery();
    }
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  // console.log(row);
  
  reset();
  const _id = row.id || ids.value;
  getManagement(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单管理";
  });
}
/** 查看订单详情 */
function check(row) {
  // 把 row 对象转为 JSON 字符串
  const rowStr = JSON.stringify(row);  
  router.push({ path: "/dingdan/ding/orderXq", 
  query: { management: rowStr } });
  
}


import { useUserStore } from '@/store/modules/user'
import { ref } from "vue";

// 获取若依用户信息
const userStore = useUserStore()
// console.log('用户信息：', userStore)
// console.log('用户信息：', userStore.id)

// const user = userStore.userInfo



/** 退款逻辑 */
// function submitForm() {

//   const addForm ={
//     orderNo:form.value.orderNo,
//     applicant:form.value.applicant,
//     reason:form.value.refundReason,
//     status:0
//   }
//   console.log(addForm);
  
//   form.value.applicant = userStore.id;
//   console.log("订单编号",form.value.orderNo);
  
//   // console.log(form.value);
  
//   //创建退款记录
//   addRecordPro(addForm).then(response => {
//           proxy.$modal.msgSuccess("新增成功")
//           open.value = false
//           getList()
//         })
  
//   getList()
// }
function submitForm() {
  const addForm = {
    orderNo: form.value.orderNo,
    applicant: userStore.id, // 直接使用userStore.id，无需额外赋值
    refundReason: form.value.refundReason, // 参数名改为refundReason，与后端保持一致
  }
  console.log(addForm);
  
  console.log("订单编号", form.value.orderNo);
  
  // 创建退款记录
  addRecordPro(addForm).then(response => {
    proxy.$modal.msgSuccess("新增成功")
    open.value = false
    getList() // 只在成功回调中调用一次getList()
  })
}
//取消逻辑
function canclesubmitForm() {
  form.value.orderStatus = 5;
  form.value.transactionStatus = 2;
  updateManagement(form.value).then(response => {
    proxy.$modal.msgSuccess("取消成功")
    open.value = false
    getList()
  })
}

const refundForm = ref()
/** 退款按钮操作 */
function refund(row) {
  //console.log(row.orderNo);
  reset();
  const _id = row.id || ids.value;
  form.value.id = _id;
  form.value.orderNo = row.orderNo;
  open.value = true;
  title.value = "填写退款原因";
  
}

function cancle(row) {
  //console.log(row.orderNo);
  reset();
  const _id = row.id || ids.value;
  form.value.id = _id;
  form.value.orderNo = row.orderNo;
  open.value = true;
  title.value = "填写退款原因";
  
}



/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delManagement(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("取消成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "le/management/export",
    {
      ...queryParams.value,
    },
    `management_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
<style scoped>
.status-buttons {
  display: flex;
  gap: 0; /* 取消按钮组的间距 */
  background-color: #F2F2F2;
  width: 600px;
  flex-wrap: wrap;
  padding: 10px 0;
  border-radius: 10px;
  margin-bottom: 10px;
}
/* 按钮样式 */
:deep(.el-button) {
  padding: 6px 16px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

/* 默认按钮样式 */
.default-btn {
  background-color: #F2F2F2;
  color: #000000;
  border: 1px solid #F2F2F2;
}

.default-btn:hover {
  background-color: #e9ecef;
  color: #409eff;
  border-color: #c6e2ff;
}

/* 选中按钮样式 */
.active {
  background-color: white;
  color: #000000;
  border-color: white;
}

.active:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>
